<template>
  <scroll-view 
    class="contact-page"
    scroll-y
    :scroll-top="scrollTop"
    :style="{paddingTop: navBarHeight + 'px'}"
    :scroll-into-view="scrollIntoView"
    @scroll="handleScroll"
    :scroll-with-animation="true"
  >
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="status-bar" :style="{height: statusBarHeight + 'px'}"></view>
      <view class="title-bar">
        <view class="nav-container">
          <view class="left-content">
            <image src="/static/logo.png" class="nav-logo" mode="aspectFit"></image>
          </view>
          <view class="middle-content">
            <text class="title">联系人</text>
          </view>
          <view class="right-content">
            <uni-icons type="personadd" size="24" color="#333" @click="handleAddFriend"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content">
      <!-- 搜索框 -->
      <view 
        class="search-box" 
        @click="handleSearch"
        @touchstart="handleTouchStart('search')"
        @touchend="handleTouchEnd"
        @touchcancel="handleTouchEnd"
        :class="{ 'active': activeElement === 'search' }"
      >
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <text class="search-placeholder">搜索</text>
      </view>

      <!-- 新朋友/群通知入口 -->
      <view class="entry-list">
        <view 
          class="entry-item" 
          @click="navigateTo('Friend')"
          @touchstart="handleTouchStart('newFriend')"
          @touchend="handleTouchEnd"
          @touchcancel="handleTouchEnd"
          :class="{ 'active': activeElement === 'newFriend' }"
        >
          <text class="item-text">新朋友</text>
          <uni-icons type="right" size="18" color="#999"></uni-icons>
        </view>
        <view 
          class="entry-item" 
          @click="navigateTo('GroupNotice')"
          @touchstart="handleTouchStart('groupNotice')"
          @touchend="handleTouchEnd"
          @touchcancel="handleTouchEnd"
          :class="{ 'active': activeElement === 'groupNotice' }"
        >
          <text class="item-text">群通知</text>
          <uni-icons type="right" size="18" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 标签页切换 -->
      <view class="tab-container">
        <view 
          class="tab-item" 
          :class="{ 'active': currentTab === 'friends' }"
          @click="switchTab('friends')"
        >
          好友
        </view>
        <view 
          class="tab-item" 
          :class="{ 'active': currentTab === 'groups' }"
          @click="switchTab('groups')"
        >
          分组
        </view>
        <view 
          class="tab-item" 
          :class="{ 'active': currentTab === 'chatGroups' }"
          @click="switchTab('chatGroups')"
        >
          群聊
        </view>
      </view>

      <!-- 标签内容区域 -->
      <view class="tab-content">
        <!-- 好友列表 -->
        <view v-if="currentTab === 'friends'">
          <view class="friend-list">
            <uni-group 
              v-for="(group, index) in friendList" 
              :key="index" 
              :title="group.letter"
            >
              <view 
                v-for="(friend, friendIndex) in group.friends" 
                :key="friendIndex"
                class="friend-item"
                @click="navigateToFriend(friend.id)"
              >
                <image class="avatar" :src="friend.avatar" mode="aspectFill"></image>
                <text class="name">{{ friend.name }}</text>
              </view>
            </uni-group>
          </view>
        </view>

        <!-- 分组列表 -->
        <view v-else-if="currentTab === 'groups'">
          <uni-collapse>
            <uni-collapse-item title="特别关心" :show-arrow="false">
              <view class="group-list">
                <view class="group-item" v-for="item in specialGroups" :key="item.id" @click="navigateToGroup(item.id)">
                  <image :src="item.avatar" class="group-avatar"></image>
                  <view class="group-info">
                    <text class="group-name">{{ item.name }}</text>
                  </view>
                </view>
              </view>
            </uni-collapse-item>
            <uni-collapse-item title="我的好友" :show-arrow="false">
              <view class="group-list">
                <view class="group-item" v-for="item in myFriendsGroups" :key="item.id" @click="navigateToGroup(item.id)">
                  <image :src="item.avatar" class="group-avatar"></image>
                  <view class="group-info">
                    <text class="group-name">{{ item.name }}</text>
                  </view>
                </view>
              </view>
            </uni-collapse-item>
            <uni-collapse-item title="朋友" :show-arrow="false">
              <view class="group-list">
                <view class="group-item" v-for="item in friendGroups" :key="item.id" @click="navigateToGroup(item.id)">
                  <image :src="item.avatar" class="group-avatar"></image>
                  <view class="group-info">
                    <text class="group-name">{{ item.name }}</text>
                  </view>
                </view>
              </view>
            </uni-collapse-item>
            <uni-collapse-item title="家人" :show-arrow="false">
              <view class="group-list">
                <view class="group-item" v-for="item in familyGroups" :key="item.id" @click="navigateToGroup(item.id)">
                  <image :src="item.avatar" class="group-avatar"></image>
                  <view class="group-info">
                    <text class="group-name">{{ item.name }}</text>
                  </view>
                </view>
              </view>
            </uni-collapse-item>
            <uni-collapse-item title="同学" :show-arrow="false">
              <view class="group-list">
                <view class="group-item" v-for="item in classmateGroups" :key="item.id" @click="navigateToGroup(item.id)">
                  <image :src="item.avatar" class="group-avatar"></image>
                  <view class="group-info">
                    <text class="group-name">{{ item.name }}</text>
                  </view>
                </view>
              </view>
            </uni-collapse-item>
          </uni-collapse>
        </view>

        <!-- 群聊列表 -->
        <view v-else-if="currentTab === 'chatGroups'">
          <uni-collapse>
            <uni-collapse-item title="我创建的群聊" :show-arrow="false">
              <view class="group-list">
                <view class="group-item" v-for="group in createdGroups" :key="group.id" @click="navigateToChatGroup(group.id)">
                  <image :src="group.avatar" class="group-avatar"></image>
                  <view class="group-info">
                    <text class="group-name">{{ group.name }}</text>
                  </view>
                </view>
              </view>
            </uni-collapse-item>
            <uni-collapse-item title="我管理的群聊" :show-arrow="false">
              <view class="group-list">
                <view class="group-item" v-for="group in managedGroups" :key="group.id" @click="navigateToChatGroup(group.id)">
                  <image :src="group.avatar" class="group-avatar"></image>
                  <view class="group-info">
                    <text class="group-name">{{ group.name }}</text>
                  </view>
                </view>
              </view>
            </uni-collapse-item>
            <uni-collapse-item title="我加入的群聊" :show-arrow="false">
              <view class="group-list">
                <view class="group-item" v-for="group in joinedGroups" :key="group.id" @click="navigateToChatGroup(group.id)">
                  <image :src="group.avatar" class="group-avatar"></image>
                  <view class="group-info">
                    <text class="group-name">{{ group.name }}</text>
                  </view>
                </view>
              </view>
            </uni-collapse-item>
          </uni-collapse>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getStatusBarHeight, getTitleBarHeight } from '@/utils/system.js';

// 引入拼音转换库（需先安装：npm install pinyin）
import pinyin from 'pinyin';

// 系统信息
const statusBarHeight = ref(0);
const titleBarHeight = ref(0);
const navBarHeight = ref(0);

// 标签页管理
const currentTab = ref('friends');

// 滚动相关
const scrollTop = ref(0);
const scrollIntoView = ref('');

// 原始好友数据
const rawFriendList = ref([
  { id: 1, name: '阿榜', avatar: '/static/logo.png' },
  { id: 2, name: 'AC。', avatar: '/static/logo.png' },
  { id: 3, name: '阿纯', avatar: '/static/logo.png' },
  { id: 4, name: 'A华硕电脑', avatar: '/static/logo.png' },
  { id: 5, name: 'Ai洋洋技术分享', avatar: '/static/logo.png' },
  { id: 6, name: '八宝', avatar: '/static/logo.png' },
  { id: 7, name: '白袍', avatar: '/static/logo.png' },
  { id: 8, name: '贝姐', avatar: '/static/logo.png' },
  { id: 9, name: '菜菜', avatar: '/static/logo.png' },
  { id: 10, name: '陈哈哈', avatar: '/static/logo.png' },
  { id: 11, name: '测试账号', avatar: '/static/logo.png' },
  { id: 12, name: '张三', avatar: '/static/logo.png' },
  { id: 13, name: '李四', avatar: '/static/logo.png' },
  { id: 14, name: '王五', avatar: '/static/logo.png' },
  { id: 15, name: '赵六', avatar: '/static/logo.png' },
]);

// 处理后的分组数据
const friendList = ref([]);

// 分组数据
const specialGroups = ref([
  { id: 1, name: '特别关心', avatar: '/static/logo.png' }
]);

const myFriendsGroups = ref([
  { id: 2, name: '我的好友', avatar: '/static/logo.png' }
]);

const friendGroups = ref([
  { id: 3, name: '朋友', avatar: '/static/logo.png' },
  { id: 4, name: '同事', avatar: '/static/logo.png' },
]);

const familyGroups = ref([
  { id: 5, name: '家人', avatar: '/static/logo.png' },
  { id: 6, name: '亲戚', avatar: '/static/logo.png' },
]);

const classmateGroups = ref([
  { id: 7, name: '小学同学', avatar: '/static/logo.png' },
  { id: 8, name: '中学同学', avatar: '/static/logo.png' },
  { id: 9, name: '大学同学', avatar: '/static/logo.png' },
]);

// 群聊数据
const createdGroups = ref([
  { id: 1, name: '清风学习交流群', avatar: '/static/logo.png' },
  { id: 2, name: '小组讨论群', avatar: '/static/logo.png' }
]);

const managedGroups = ref([
  { id: 3, name: '管理群示例', avatar: '/static/logo.png' }
]);

const joinedGroups = ref([
  { id: 4, name: '示例群1', avatar: '/static/logo.png' },
  { id: 5, name: '示例群2', avatar: '/static/logo.png' },
  { id: 6, name: '示例群3', avatar: '/static/logo.png' },
]);

// 点击状态管理
const activeElement = ref('');

onMounted(() => {
  // 获取系统状态栏高度
  statusBarHeight.value = getStatusBarHeight();
  titleBarHeight.value = getTitleBarHeight();
  navBarHeight.value = statusBarHeight.value + titleBarHeight.value;
  
  // 生成按拼音首字母分组的好友列表
  generateFriendGroups();
});

// 生成按拼音首字母分组的好友列表
const generateFriendGroups = () => {
  // 初始化分组结构（A-Z + 其他）
  const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
  const otherLetter = '其他';
  const initialGroups = letters.reduce((acc, letter) => {
    acc[letter] = [];
    return acc;
  }, { [otherLetter]: [] });

  // 按首字母归类好友
  rawFriendList.value.forEach(friend => {
    const firstChar = friend.name.charAt(0);
    let firstLetter = '';
    
    // 判断是否为中文
    const isChinese = /[\u4e00-\u9fa5]/.test(firstChar);
    
    if (isChinese) {
      // 中文字符：使用拼音转换库获取首字母
      const pyResult = pinyin(firstChar, { style: pinyin.STYLE_FIRST_LETTER });
      firstLetter = pyResult[0][0].toUpperCase();
    } else {
      // 非中文字符：直接取首字母并大写
      firstLetter = firstChar.toUpperCase();
    }
    
    // 判断首字母是否为A-Z
    if (letters.includes(firstLetter)) {
      initialGroups[firstLetter].push(friend);
    } else {
      initialGroups[otherLetter].push(friend);
    }
  });

  // 过滤空分组，生成最终列表
  friendList.value = Object.entries(initialGroups)
    .filter(([_, friends]) => friends.length > 0)
    .map(([letter, friends]) => ({ letter, friends }));
};

// 处理触摸事件
const handleTouchStart = (element) => {
  activeElement.value = element;
};

const handleTouchEnd = () => {
  setTimeout(() => {
    activeElement.value = '';
  }, 200); // 保持200ms的点击效果
};

// 处理滚动事件
const handleScroll = (e) => {
  scrollTop.value = e.detail.scrollTop;
};

// 切换标签页
const switchTab = (tabName) => {
  currentTab.value = tabName;
};

// 导航方法
const navigateTo = (path) => {
  uni.navigateTo({
  	url:"/pages/chat/" + path
  })
};

const navigateToFriend = (friendId) => {
};

const navigateToGroup = (groupId) => {
  
};

const navigateToChatGroup = (groupId) => {
  console.log(`进入群聊: ${groupId}`);
  // 实际项目中使用: uni.navigateTo({ url: `/pages/chatGroup/chatGroup?id=${groupId}` });
};

// 搜索功能
const handleSearch = () => {
 uni.navigateTo({
 	url:"/pages/common/search"
 })
};

// 添加好友
const handleAddFriend = () => {
  uni.navigateTo({
  	url:"/pages/chat/AddFriend"
  })
};

</script>

<style lang="scss" scoped>
.contact-page {
  height: 100vh;
  background-color: #f8f8f8;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  
  // 隐藏原生滚动条
  ::-webkit-scrollbar {
    width: 0;
    height: 0;
    background-color: transparent;
  }

  // 顶部导航栏
  .navbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background-color: #fff;

    .status-bar {
      background-color: #fff;
    }

    .title-bar {
      height: 44px;
      display: flex;
      align-items: center;
      padding: 0 15px;

      .nav-container {
        width: 100%;
        display: flex;
        align-items: center;

        .left-content {
          flex: 0 0 40px;

          .nav-logo {
            width: 30px;
            height: 30px;
            border-radius: 5px;
          }
        }

        .middle-content {
          flex: 1;
          text-align: center;

          .title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
          }
        }

        .right-content {
          flex: 0 0 40px;
          text-align: right;
        }
      }
    }
  }

  // 内容区域
  .content {
    padding-top: calc(var(--status-bar-height) + 44px);
    padding-bottom: 50px;

    // 搜索框
    .search-box {
      height: 34px;
      margin: 10px;
      background-color: #f2f2f2;
      border-radius: 17px;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: background-color 0.2s;

      .search-placeholder {
        margin-left: 5px;
        font-size: 14px;
        color: #999;
      }

      // 点击状态
      &.active {
        background-color: #e8e8e8;
      }
    }

    // 入口列表
    .entry-list {
      background-color: #fff;
      margin-top: 10px;

      .entry-item {
        height: 50px;
        padding: 0 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #f2f2f2;
        transition: background-color 0.2s;

        .item-text {
          font-size: 16px;
          color: #333;
        }

        // 点击状态
        &.active {
          background-color: #f5f5f5;
        }
      }
    }

    // 标签页容器
    .tab-container {
      display: flex;
      height: 40px;
      background-color: #fff;
      margin-top: 10px;

      .tab-item {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        color: #666;
        position: relative;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          width: 30px;
          height: 2px;
          background-color: transparent;
          transform: translateX(-50%);
        }

        &.active {
          color: #07c160;

          &::after {
            background-color: #07c160;
          }
        }
      }
    }

    // 标签内容区域
    .tab-content {
      .empty-list {
        padding: 20px;
        text-align: center;
        font-size: 14px;
        color: #999;
      }

      // 好友列表
      .friend-list {
        background-color: #fff;

        .friend-item {
          height: 60px;
          padding: 0 15px;
          display: flex;
          align-items: center;
          border-bottom: 1px solid #f2f2f2;
          transition: background-color 0.2s;

          &:hover {
            background-color: #f8f8f8;
          }

          .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #f2f2f2;
          }

          .name {
            margin-left: 10px;
            font-size: 16px;
            color: #333;
          }
        }
      }

      // 分组和群聊共用的折叠面板样式
      uni-collapse {
        background-color: #fff;
        margin-top: 10px;
      }

      uni-collapse-item {
        border-bottom: 1px solid #f2f2f2;
      }

      .group-list {
        .group-item {
          display: flex;
          align-items: center;
          padding: 10px 15px;
          border-bottom: 1px solid #f2f2f2;
          transition: background-color 0.2s;

          &:hover {
            background-color: #f8f8f8;
          }

          .group-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #f2f2f2;
          }

          .group-info {
            flex: 1;
            margin-left: 10px;

            .group-name {
              font-size: 16px;
              color: #333;
            }
          }
        }
      }
    }
  }
}
</style>